package com.party.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.party.domain.Signin;
import com.party.domain.User;
import com.party.dto.Response;
import com.party.service.impl.UserServiceImpl;
import com.party.tool.CookieUtils;





@RestController
@RequestMapping("/user")
public class LoginController
{
	private final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private UserServiceImpl  ptservice;
	
	@Autowired
	HttpServletResponse response;
	@Autowired
	HttpServletRequest request;
	
	private String status="error";
	
	
	
	//登录
/*	@RequestMapping(value="/login")
	public Response LoginUser(String Email,String Password) throws UnsupportedEncodingException
	{
		try {
			User user=ptservice.loginCheck(Email, Password);
			if(!StringUtils.isEmpty(user))
			{
				CookieUtils.addCookie(response,user);	
				return Response.success(user);
			}
			else if(StringUtils.isEmpty(user))
			return Response.failure("帐号未注册或未激活");
			
			return Response.failure("帐号未注册或未激活");
		} catch (Exception e) {
			return Response.failure("帐号未注册或未激活");
		}
		
		
		
	}*/
	
/*	//登陆成功
	@RequestMapping("/success")
	public Response loginSuccess(){
		return Response.success();
	}
	
	//登录失败
	@RequestMapping("/failue")
	public Response loginFailue(HttpSession session){
		Exception e= (Exception) session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
		if(e.getMessage().equals("Bad credentials"))
			return Response.failure("密码错误");
		return Response.failure(e.getMessage());
	}*/
	//激活
	@RequestMapping(value="/activate")
	public Response Activate(String Email)
	{
		try {
			if(ptservice.activateUser(Email).equals("success"))
				return Response.success("激活成功");
			
			return Response.failure("激活失败");
		} catch (Exception e) {
			return Response.failure("激活失败");
		}
		
		
		
	}
	
	//检测邮箱是否被注册
	@RequestMapping(value="/emailno")
	public Response emailNoUse(String Email)
	{
		try {
			User user=ptservice.whetherRegister(Email);
			if(!StringUtils.isEmpty(user))
			{
				return Response.failure("该邮箱已被注册");
			}
			else if(StringUtils.isEmpty(user))
			return Response.success("该邮箱未被使用");
			
			return Response.success("未知错误,请重试");
		} catch (Exception e) {
			return Response.success("未知错误");
		}

		
	}
	
	
	
	//发送修改密码邮件
	@RequestMapping(value="/passwordemail")
	public Response Password(String Email,String Password)
	{
		
		try {
			if(ptservice.sendPasswordEmail(Email, Password).equals("success"))
				return Response.success("修改密码邮件已发送");
			return Response.failure("修改密码邮件发送失败，请重试");
		} catch (Exception e) {
			return Response.failure("修改密码邮件发送失败，请重试");
		}
		
		
		
	}
	
	//修改密码
	@RequestMapping(value="/changepassword")
	public Response changePassword(String Email,String Password)
	{
		try {
			if(ptservice.ChangeUserPassword(Email, Password).equals("success"))
				return Response.success("修改密码成功");
			return Response.failure("修改密码失败,请重试");
		} catch (Exception e) {
			
			return Response.failure("修改密码失败,请重试");
		}
		

	}
	
	//修改用户头像
	@RequestMapping(value="/changeicon")
	public Response changeIcon(@RequestParam("files") MultipartFile files,HttpServletRequest request,HttpSession session)
	{
		try {
			 /*SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
		       User user = (User) context.getAuthentication().getPrincipal();*/
			   User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			   logger.info("这里已经被访问啦！");
			   System.out.println("fileName---------->" + files.getOriginalFilename());  
			String newfilename="D://" + new Date().getTime() + files.getOriginalFilename();
			if(!files.isEmpty()){  
				int pre = (int) System.currentTimeMillis();  
				
				try {  
					//拿到输出流，同时重命名上传的文件  

					FileOutputStream os = new FileOutputStream(newfilename);  
					//拿到上传文件的输入流  
					FileInputStream in = (FileInputStream) files.getInputStream();  
					  
					//以写字节的方式写文件  
					int b = 0;  
					while((b=in.read()) != -1){  
						os.write(b);  
					}  
					os.flush();  
					os.close();  
					in.close();  
					int finaltime = (int) System.currentTimeMillis();  
					System.out.println(finaltime - pre);  
					  
					ptservice.changeUserIcon(user.getId(), newfilename);
					
				} catch (Exception e) {  
					e.printStackTrace();  
					System.out.println("上传头像出错");  
				}  
		
			
			}
			return Response.success();
		} catch (Exception e) {
			return Response.failure();
		}
	
	}

	//修改用户资料
	@RequestMapping(value="editdate")
	public Response editDate(String Phones,String name,HttpSession session)
	{
		System.out.println(name);
		SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
	       User user = (User) context.getAuthentication().getPrincipal();
		ptservice.changeUserDate(Phones, name, user.getId());
		return Response.success();
	}
	
	
	 @RequestMapping(value="/showCookies")  
     public Response showCookies(HttpServletRequest request,HttpServletResponse response,HttpSession session ){  
		 //方式一
     /*  SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
       User user = (User) context.getAuthentication().getPrincipal();*/
		 //方式二
//		 User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       String q=CookieUtils.getCookie(request, "id");
       System.out.println(q);
       return Response.success();
            
     }  
	

	   @RequestMapping(value="/delCookie")
       public void delCookie(HttpServletRequest request,HttpServletResponse response,String name){
           Cookie[] cookies = request.getCookies();
           if (null==cookies) {
               System.out.println("没有cookie==============");
           } else {
               for(Cookie cookie : cookies){
                   if(cookie.getName().equals(name)){
                       cookie.setValue(null);
                       cookie.setMaxAge(0);// 立即销毁cookie
                       cookie.setPath("/");
                       System.out.println("被删除的cookie名字为:"+cookie.getName());
                       response.addCookie(cookie);
                       break;
                   }
               }
           }
       }
	 
	//注册
	@RequestMapping(value="/register")
	public Response Raegister(String Email,String Password,String Name,String Phones,String state/*,@RequestParam("file") MultipartFile[] files,HttpServletRequest request*/)
	{

		try 
		{
			status=state;
			if(status.equals("success"))
			{				
				if(ptservice.sendRegisterEmail(Email).equals("success"))
				{
	
					User user=ptservice.userREgisterInit(Email, Password, Name, Phones, state);
					int uid=ptservice.userRegister(user);
					System.out.println("ssssssssssssssssssssssssssssss"+uid);
					ptservice.addUserRole(uid);
					}
					
					
				
			}
			return Response.success("邮件已发送");
		} catch (Exception e) {
			logger.error("获取用户出错", e);
			return Response.failure("邮件发送失败，重新发送");
		}	
	}
	
	
	//用户信息
	@RequestMapping(value="/userMessage")
	public Response UserMessage(HttpSession session)
	{
		try {
			SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
		       User user = (User) context.getAuthentication().getPrincipal();
			//String email=CookieUtils.getCookie(request, "email");
			Object users=ptservice.getUserMessage(user.getId());
			logger.info("获取用户完成"+ JSON.toJSONString(user));
			return Response.success(users);
		} catch (Exception e) {
			logger.error("获取用户出错", e);
			return Response.failure("获取用户信息失败");
		}
		
	}
	
	
	//签到
	@RequestMapping(value="/signin")
	public Response userSignIn(HttpSession session)
	{
		try {
			SecurityContext context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
		       User user = (User) context.getAuthentication().getPrincipal();
		       int id=user.getId();
			Signin signin=ptservice.findSignin(id);

			if(StringUtils.isEmpty(signin))
			{		
				//没查询到就插入
				ptservice.insterSigninUser(id, new java.sql.Date(new java.util.Date().getTime()));
				
				return Response.success("签到成功");
			}
			//检查今天是否签到过了
			if(ptservice.judgeTime(signin.getTime(), new java.sql.Date(new java.util.Date().getTime())))
			{
				if(ptservice.UpdateUserIntegral(id))return Response.success("签到成功");
				else return Response.failure("签到失败，请重试");
			}
			return Response.failure("今天已经签过了");
		} catch (Exception e) {
			logger.error("出错了", e);
			return Response.failure("未知错误");
		}
		
	}
	
	
	
	//增加管理员帐号接口
	@RequestMapping(value="/addManage")
	public Response addManage(User user)
	{
		try {
			logger.info("增加管理员帐号中");
			int uid=ptservice.addAdminUser(user);
			logger.info("增加管理员帐号成功");
			 
			 
			logger.info("增加管理员权限中");
			ptservice.addRoleAdmin(uid);
			logger.info("增加管理员权限成功");
			return Response.success();
		} catch (Exception e) {
			return Response.failure();
		}
	}
	
	//查询所有帐号接口
	@RequestMapping(value="/findAllUserData")
	public Response findAllUserData(int page,int size)
	{
		try {
			logger.info("查询所有用户中");
			List<User> user=ptservice.findAllUser(page, size);
			logger.info("查询所有用户成功");
			
			return Response.success(user);
		} catch (Exception e) {
			return Response.failure();
		}
	}
	
	//管理员更新用户所有数据接口
	@RequestMapping(value="/updateAll")
	public Response updateAll(User user,int role_id)
	{
		try {
			logger.info("更新用户所有数据中");
			ptservice.updateAllDate(user,role_id);
			logger.info("更新用户所有数据成功");
			return Response.success();
		} catch (Exception e) {
			return Response.failure();
		}
	}
	
	
	@RequestMapping(value="/ceshi")
	public void ceshia(int id)
	{
		ptservice.UpdateUserIntegral(id);
	}
	
}
